<template>
  <!-- 角色表单弹窗 -->
  <el-dialog
    v-model="dialog.visible"
    title="编辑账户"
    width="500px"
    height="500px"
    @close="handleCloseDialog"
  >
    <el-form :model="formData" label-width="100px" :rules="rules">
      <el-form-item label="子账户名称" style="width: 90%" prop="virtualName">
        <el-input v-model="formData.virtualName" placeholder="请输入子账户名称" size="large" />
      </el-form-item>
      <el-form-item label="角色" style="width: 90%" prop="roleId">
        <el-select v-model="formData.roleId" placeholder="Select" size="large">
          <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="handleCloseDialog">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import TermAPI from "@/api/term";
import RoleAPI from "@/api/system/role";
import CommonAPI from "@/api/system/common";
import { ElMessage } from "element-plus";
// 定义 emit，用于通知外部关闭事件
const emit = defineEmits(["update:modelValue", "handleBindSubmit"]);
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false,
  },
  defaultRow: {
    type: Object,
    default: () => {},
  },
});
const formData = ref({
  roleId: "",
  virtualName: "",
});
const rules = ref({
  roleId: [{ required: true, message: "请选择角色", trigger: "change" }],
  virtualName: [{ required: true, message: "请输入子账户名称", trigger: "blur" }],
});
const options = ref([]);
const getRoleList = async () => {
  try {
    const data = await RoleAPI.getPage({
      pageNum: 1,
      pageSize: 1000,
    });
    options.value = data.list;
  } catch (err) {
    console.log(err);
  }
};

const handleSubmit = async (roleId) => {
  try {
    const data = await TermAPI.editRole({
      id: props.defaultRow.id,
      roleId: formData.value.roleId,
      virtualName: formData.value.virtualName,
    });

    dialog.visible = false;
    emit("update:modelValue", false); // 关闭弹窗
    emit("handleEditSuccess");
  } catch (err) {
    console.log(err);
  }
};
/***
 *
 * 弹框操作
 */
const dialog = reactive({
  title: "",
  visible: false,
});
// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  emit("update:modelValue", false); // 关闭弹窗
}
// 监听外部传入的 modelValue，更新内部 visible 状态
watch(
  () => props.modelValue,
  (newValue) => {
    dialog.visible = newValue;
  }
);
watch(
  () => props.defaultRow,
  (newValue) => {
    if (newValue) {
      formData.value.roleId = newValue.roleId;
      formData.value.virtualName = newValue.virtualName;
    }
  },
  {
    immediate: true,
  }
);
onMounted(() => {
  getRoleList();
});
</script>
<style style="scss" scoped>
::v-deep(.el-tabs__content) {
  min-height: 100px;
  display: flex;
  align-items: center;
}
</style>
